package com.zxl.admin.controller.login;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zxl.admin.annotation.NoPower;
import com.zxl.admin.base.LoginResult;
import com.zxl.admin.context.UserContext;
import com.zxl.common.Result;
import com.zxl.common.constant.ResponseStatusCode;
import com.zxl.common.exception.LoginException;
import com.zxl.common.mapper.SysUserMapper;
import com.zxl.common.model.bo.login.LoginBo;
import com.zxl.common.model.pojo.SysUser;
import com.zxl.common.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * @author zxw
 * @date 2023/3/31
 */
@Api(tags = "登录管理")
@RestController
@RequestMapping("/admin/user_login")
public class UserLoginController {

    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysUserMapper sysUserMapper;

    @PostMapping("/login")
    @ApiOperation("后台登录")
    @NoPower
    public LoginResult login(@Valid @RequestBody LoginBo loginBo){
        if (StringUtils.isBlank(loginBo.getPassword()) || StringUtils.isBlank(loginBo.getUserName())) {
            throw new LoginException(LoginException.ACCOUNT_IS_NULL_ERROR);
        }
        SysUser user = sysUserService.validUserCode(loginBo.getUserName());
        if (user == null) {
            throw new LoginException(LoginException.LOGIN_ACCOUNT_PASSWD_ERROR);
        }

        if (!sysUserService.validPasswd(user.getUserName(), SaSecureUtil.sha256(user.getSalt() + loginBo.getPassword()))) {
            throw new LoginException(LoginException.LOGIN_ACCOUNT_PASSWD_ERROR);
        }

        StpUtil.login(user.getId());
        sysUserMapper.update(null, new UpdateWrapper<SysUser>()
                .eq("id", user.getId())
                .set("token", StpUtil.getTokenValue()));
        Result result = new Result(StpUtil.getTokenValue(), ResponseStatusCode.SUCCESS.getCode(), LoginException.LOGIN_SUCCESS, true);
        return new LoginResult(result, ResponseStatusCode.SUCCESS.getMessage(), user.getUserName(), user.getId());
    }



    @GetMapping("/login_out")
    @ApiOperation("注销登录")
    @NoPower
    public Result loginOut() {
        Integer userId = UserContext.getUserId();
        sysUserService.update(new UpdateWrapper<SysUser>()
                .eq("id",userId)
                .set("token",""));

        return new Result(ResponseStatusCode.SUCCESS.getCode(),LoginException.LOG_OUT_SUCCESS);
    }
}
